﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Telerik.Web.UI;
using System.Text;

namespace BEGDC.CC.Web.Common
{
    public partial class VelaPagerI : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            //this.ParentGrid.MasterTableView.NoMasterRecordsText = Resources.VelaLanguage.NoRecords;

            btnFirst.ImageUrl = "~/images/pg_first.gif";
            btnPrev.ImageUrl = "~/images/pg_pre.gif";
            btnNext.ImageUrl = "~/images/pg_next.gif";
            btnLast.ImageUrl = "~/images/pg_last.gif";
            btnGo.ImageUrl = "~/images/PageIcon.gif";
            if (this.Width == string.Empty)
            {
                this.Width = this.ParentGrid.Width.ToString();
            }
            if (this.AllowSort)
            {
                this.ParentGrid.SortCommand += ParentGrid_OnSortCommand;
            }

            if (this.AutoLoading)
            {
                RadAjaxManager manage;

                if (this.ParentManager != null)
                {
                    manage = this.ParentManager;
                }
                else
                {
                    throw new Exception("It need a RadAjaxManager when AutoLoading");
                }
                //RadAjaxLoadingPanel loading;
                string loading = string.Empty;
                if (this.ParentLoading != null)
                {
                    loading = this.ParentLoading.ID;
                }

                AjaxSetting setting;
                if (this.ParentPanel != null)
                {
                    this.ParentPanel.LoadingPanelID = loading;
                    //setting = new AjaxSetting(this.ParentPanel.ID);
                    //setting.UpdatedControls.Add(new AjaxUpdatedControl(this.ParentPanel.ID, loading));
                    //if (manage.AjaxSettings.IndexOf(setting) < 0)
                    //{
                    //    manage.AjaxSettings.Add(setting);
                    //}
                }
                else
                {
                    setting = new AjaxSetting(this.ParentGrid.ID);
                    setting.UpdatedControls.Add(new AjaxUpdatedControl(this.ParentGrid.ID, loading));
                    setting.UpdatedControls.Add(new AjaxUpdatedControl(this.ID, string.Empty));
                    if (manage.AjaxSettings.IndexOf(setting) < 0)
                    {
                        manage.AjaxSettings.Add(setting);
                    }
                    setting = new AjaxSetting(this.ID);
                    setting.UpdatedControls.Add(new AjaxUpdatedControl(this.ParentGrid.ID, loading));
                    setting.UpdatedControls.Add(new AjaxUpdatedControl(this.ID, string.Empty));
                    if (manage.AjaxSettings.IndexOf(setting) < 0)
                    {
                        manage.AjaxSettings.Add(setting);
                    }
                }

            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.Visible = this.IsAlwaysVisible && this.IsQueryed;
                PagerTable.Attributes["class"] = "GridPager_" + this.Skin;
                rtxtPageIndex.Value = 1;
            }
        }
        #region 属性
        private RadGrid _parent;
        private RadAjaxPanel _parentPanel;
        private RadAjaxManager _parentManage;
        private RadAjaxLoadingPanel _parentLoading;

        private object _dataSource;
        public string ParentGridID
        {
            get { return hidParentGridID.Value; }
            set { hidParentGridID.Value = value; }
        }

        public string Skin
        {
            get { return hidSkin.Value; }
            set { hidSkin.Value = value; }
        }

        public bool IsQueryed
        {
            get
            {
                bool temp;
                bool.TryParse(hidQuery.Value, out temp);
                return temp;
            }
            set { hidQuery.Value = value.ToString(); }
        }

        public bool IsAlwaysVisible
        {
            get
            {
                bool temp;
                if (!bool.TryParse(hidVisible.Value, out temp))
                {
                    return true;
                }
                return temp;
            }
            set { hidVisible.Value = value.ToString(); }
        }

        public bool AllowSort
        {
            get
            {
                bool temp;
                bool.TryParse(hidAllowSort.Value, out temp);
                return temp;
            }
            set { hidAllowSort.Value = value.ToString(); }
        }

        public bool AutoLoading
        {
            get
            {
                bool temp;
                bool.TryParse(hidLoading.Value, out temp);
                return temp;
            }
            set { hidLoading.Value = value.ToString(); }
        }

        public RadGrid ParentGrid
        {
            get
            {
                if (_parent == null)
                {
                    _parent = GetParentGrid();
                }
                return _parent;
            }
        }

        public RadAjaxPanel ParentPanel
        {
            get
            {
                if (_parentPanel == null)
                {
                    _parentPanel = GetParentPanel();
                }
                return _parentPanel;
            }
        }

        public RadAjaxManager ParentManager
        {
            get
            {
                if (_parentManage == null)
                {
                    _parentManage = GetParentManager();
                }
                return _parentManage;
            }
        }

        public RadAjaxLoadingPanel ParentLoading
        {
            get
            {
                if (_parentLoading == null)
                {
                    _parentLoading = GetParentLoading();
                }
                return _parentLoading;
            }
        }

        public object DataSource
        {
            get { return _dataSource; }
            set { _dataSource = value; }
        }

        public int PageSize
        {
            get { return ParentGrid.PageSize; }
        }

        public string Width
        {
            get { return PagerTable.Width; }
            set { PagerTable.Width = value; }
        }

        public int PageCount
        {
            get
            {
                if (PageSize == 0)
                {
                    return 1;
                }
                int count = RowsCount / PageSize;
                int temp = RowsCount - count * PageSize;
                return temp > 0 ? count + 1 : count;
            }
        }

        public int PageIndex
        {
            get
            {
                int temp;
                int.TryParse(hidPageIndex.Value, out temp);
                return temp;
            }
            set { hidPageIndex.Value = value.ToString(); }

        }

        public int RowsCount
        {
            get
            {
                int temp;
                int.TryParse(hidRowsCount.Value, out temp);
                return temp;
            }
            set { hidRowsCount.Value = value.ToString(); }

        }

        ///<summary>
        ///初次查询的排序字段
        ///</summary>
        private string MaidenSortString
        {
            get
            {
                return hidMaidenSortString.Value;
            }

            set { hidMaidenSortString.Value = value; }
        }

        ///<summary>
        ///给SortString赋值时，如果排序列为Grid的排序字段则自动更改Grid的排序状态。
        ///如果排序列不是Grid的排序字段则为隐藏排序列，Grid没有排序状态时，按照隐藏排序列排序。
        ///默认隐藏排序列为ParentGrid的DataKeyNames升序
        ///</summary>
        public string SortString
        {
            get
            {
                StringBuilder sb = new StringBuilder();
                if (this.ParentGrid.MasterTableView.SortExpressions.Count > 0)
                {
                    foreach (GridSortExpression exp in this.ParentGrid.MasterTableView.SortExpressions)
                    {
                        sb.AppendFormat("{0},", exp.ToString());
                    }

                }
                else
                {
                    if (MaidenSortString.Length > 0)
                    {
                        sb.Append(MaidenSortString);
                    }
                    else
                    {
                        foreach (string exp in this.ParentGrid.MasterTableView.DataKeyNames)
                        {
                            sb.AppendFormat("{0} asc,", exp);
                        }
                    }
                }
                //if (sb.Length > 0)
                //{
                //    sb.Remove(sb.Length - 1, 1);
                //}
                return sb.ToString().Trim().TrimEnd(',');
            }
            set
            {
                string[] sorts = value.Trim().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (sorts.Length == 0)
                {
                    MaidenSortString = string.Empty;
                }
                else if (sorts.Length > 1)
                {
                    MaidenSortString = value.Trim().TrimEnd(',');
                }
                else
                {
                    string[] sort = sorts[0].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (GridColumn column in ParentGrid.MasterTableView.Columns)
                    {
                        if (column.SortExpression.ToLower() == sort[0].ToLower())
                        {
                            GridSortExpression exp = new GridSortExpression();
                            exp.FieldName = column.SortExpression;
                            exp.SortOrder = sort.Length == 1 || sort[1].ToLower() == "asc" ? GridSortOrder.Ascending : GridSortOrder.Descending;

                            ParentGrid.MasterTableView.SortExpressions.AddSortExpression(exp);
                            return;
                        }
                    }
                    MaidenSortString = sorts[0];

                }
            }
        }

        #endregion


        #region 方法
        public void Query()
        {
            rtxtPageIndex.Value = 1;
            PageIndex = 1;
            //this.ParentGrid.MasterTableView.SortExpressions.Clear();
            LoadGrid();
        }

        public void Refresh()
        {
            LoadGrid();
        }

        private void LoadGrid()
        {
            OnNeedDataSource(new PagerEventArgs());
            this.PageIndex = Math.Min(this.PageIndex, this.PageCount);
            Bind();
        }

        private void Bind()
        {
            Bind(false);
        }

        private void Bind(bool isLast)
        {
            RadGrid grid = ParentGrid;

            ChangeButton(isLast);
            grid.DataSource = this.DataSource;
            grid.Rebind();
        }

        public void Sort(GridSortCommandEventArgs e)
        {
            rtxtPageIndex.Value = 1;
            PageIndex = 1;

            GridSortExpression sort = new GridSortExpression();
            sort.FieldName = e.SortExpression;
            sort.SortOrder = e.NewSortOrder;
            GridSortExpressionCollection list = this.ParentGrid.MasterTableView.SortExpressions;

            if (sort.SortOrder != GridSortOrder.None)
            {
                list.ChangeSortOrder(sort.ToString());
            }
            else
            {
                list.Clear();
            }
            LoadGrid();
            e.Canceled = true;
        }

        private RadGrid GetParentGrid(System.Web.UI.Control control)
        {
            while (control != null && !(control is RadGrid))
            {
                control = control.Parent;

            }
            if (control == null)
            {
                throw new Exception("This Control must be used in RadGrid. ");
            }
            return (RadGrid)control;
        }

        private RadGrid GetParentGrid()
        {
            RadGrid control = this.Parent.FindControl(this.ParentGridID) as RadGrid;

            if (control == null)
            {
                throw new Exception("This Control must be used in control witch has a RadGrid. ");
            }
            return control;
        }

        private RadAjaxPanel GetParentPanel()
        {
            System.Web.UI.Control control = this.ParentGrid.Parent;

            while (control != null && !(control is RadAjaxPanel))
            {
                control = control.Parent;

            }

            return (RadAjaxPanel)control;
        }

        private RadAjaxManager GetParentManager()
        {
            System.Web.UI.Control control = this.ParentPanel != null ? this.ParentPanel.Parent : this.ParentGrid.Parent;

            while (control != null && !(control is Page))
            {
                foreach (System.Web.UI.Control temp in control.Controls)
                {
                    if (temp is RadAjaxManager)
                    {
                        return (RadAjaxManager)temp;
                    }
                }

                control = control.Parent;
            }

            return null;
        }

        private RadAjaxLoadingPanel GetParentLoading()
        {
            System.Web.UI.Control control = this.ParentPanel != null ? this.ParentPanel.Parent : this.ParentGrid.Parent;

            while (control != null && !(control is Page))
            {
                foreach (System.Web.UI.Control temp in control.Controls)
                {
                    if (temp is RadAjaxLoadingPanel)
                    {
                        return (RadAjaxLoadingPanel)temp;
                    }
                }

                control = control.Parent;
            }

            return null;
        }

        private void ChangeButton(bool isLast)
        {
            if (this.PageSize == 0 || RowsCount == 0)
            {
                btnFirst.Enabled = false;
                btnLast.Enabled = false;
                btnNext.Enabled = false;
                btnPrev.Enabled = false;
                btnGo.Enabled = false;
                return;
            }
            rtxtPageIndex.MaxValue = this.PageCount;
            btnFirst.Enabled = true;
            btnLast.Enabled = true;
            btnNext.Enabled = true;
            btnPrev.Enabled = true;
            btnGo.Enabled = true;
            if (isLast)
            {
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
            else if (this.PageIndex == 1)
            {
                btnFirst.Enabled = false;
                btnPrev.Enabled = false;
            }
            else if (this.PageIndex == this.PageCount)
            {
                btnNext.Enabled = false;
                btnLast.Enabled = false;
            }
        }
        #endregion

        #region 事件

        public event EventHandler<PagerEventArgs> NeedDataSource;
        protected virtual void OnNeedDataSource(PagerEventArgs e)
        {
            EventHandler<PagerEventArgs> handler = NeedDataSource;
            this.IsQueryed = true;
            this.Visible = IsAlwaysVisible;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected void ParentGrid_OnSortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
        {
            this.Sort(e);
        }

        /// <summary>
        /// 跳转
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnGo_Click(object sender, ImageClickEventArgs e)
        {
            if (!rtxtPageIndex.Value.HasValue || (int)rtxtPageIndex.Value < 1)
            {
                rtxtPageIndex.Value = 1;
            }
            this.PageIndex = (int)rtxtPageIndex.Value;
            OnNeedDataSource(new PagerEventArgs());
            Bind();
        }



        /// <summary>
        /// 第一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFirst_Click(object sender, ImageClickEventArgs e)
        {
            this.PageIndex = 1;
            OnNeedDataSource(new PagerEventArgs());
            Bind();
            rtxtPageIndex.Value = 1;
        }

        /// <summary>
        /// 最后一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLast_Click(object sender, ImageClickEventArgs e)
        {
            OnNeedDataSource(new PagerEventArgs(true));
            Bind(true);
            rtxtPageIndex.Value = this.PageCount;
            PageIndex = this.PageCount; ;
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrev_Click(object sender, ImageClickEventArgs e)
        {
            int temp = rtxtPageIndex.Value == null ? 1 : (int)rtxtPageIndex.Value;
            this.PageIndex = Math.Max(1, temp - 1);
            OnNeedDataSource(new PagerEventArgs());
            Bind();
            rtxtPageIndex.Value = Math.Min(this.PageCount, this.PageIndex);
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNext_Click(object sender, EventArgs e)
        {
            int temp = rtxtPageIndex.Value == null ? 1 : (int)rtxtPageIndex.Value;
            this.PageIndex = Math.Max(1, temp + 1);
            OnNeedDataSource(new PagerEventArgs());
            Bind();
            rtxtPageIndex.Value = Math.Min(this.PageCount, this.PageIndex);
        }
        #endregion 
    }

    public class PagerEventArgs : EventArgs
    {
        private bool _isLast;
        public bool IsLast
        {
            get { return _isLast; }
            set { _isLast = value; }
        }

        public PagerEventArgs(bool isLast)
        {
            _isLast = isLast;
        }
        public PagerEventArgs()
            : this(false)
        {

        }
    }
}